# -*- coding=utf-8 -*-
import datetime
from django.contrib import auth
from django.http import HttpResponseRedirect, HttpResponse
from django.http.response import HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.shortcuts import render
from bms.utils.page import Page


# Create your views here.
from django.template import RequestContext
from bms.models import Article, ArticleCategory, UserProfile, Tag, TagTelation

navigation = [{'name': '首页', 'url': '/index', 'active': False},
              {'name': '分类', 'url': '/blog/category', 'active': False,
               "child": [{'name': '原创', 'url': '/yuanchuang', 'active': False},
                         {'name': '收藏', 'url': '/shoucang', 'active': False},
                         {'name': '生活', 'url': '/live', 'active': False}]},
              {'name': '归档', 'url': '/article', 'active': False},
              {'name': '标签', 'url': '/tag', 'active': False},
              {'name': '关于', 'url': '/about', 'active': False}]


def index(request):
    set_navigation("/index")
    articles = Article.objects.all()
    objects, page_range = Page.build_pagination(request, articles)
    return render_to_response("index.html", {'objects': objects, 'page_range': page_range,
                                             'navigation': navigation},
                              context_instance=RequestContext(request))


def tag(request):
    nav = set_navigation("/tag")
    return render(request, "index.html", {'navigation': nav})


def about(request):
    nav = set_navigation("/about")
    return render(request, "index.html", {'navigation': nav})


def article(request):
    nav = set_navigation("/article")
    return render(request, "index.html", {'navigation': nav})


def set_navigation(url):
    for n in navigation:
        if n['url'] == url:
            n['active'] = True
        else:
            n['active'] = False
    return navigation


def to_login(request):
    return render(request, "login.html")


def to_logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/")


def admin(request):
    return render(request, "admin.html")


def admin_welcome(request):
    return render(request, "admin_welcome.html")


def article_manage(request):
    return render(request, "article-manage.html")


def create_article(request):
    categories = ArticleCategory.objects.all()
    return render_to_response("create_article.html", {'categories': categories},
                              context_instance=RequestContext(request))


def add_article(request):
    if request.method == 'POST':
        title = request.POST['title']
        category_id = request.POST['categoryId']
        content = request.POST['content']
        tags = request.POST['tags']
        tag_list = None
        if tags is not None:
            tag_list = tags.replace('，', ',').split(',')

        try:
            a = Article()
            a.title = title
            a.category_id = category_id
            a.content = content
            a.create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%I:%S")
            a.user = UserProfile.objects.get(user=auth.get_user(request))
            a.save()
            tAll = Tag.objects.all()
            for n in tag_list:
                t = tAll.filter(tag_name=n)
                if len(t) > 0:
                    t = t[0]
                else:
                    t = Tag()
                    t.tag_name = n
                    t.save()
                tt = TagTelation()
                tt.article = a
                tt.tag = t
                tt.save()
            return HttpResponse("添加文章成功")
        except Exception as ex:
            print(ex)
            return HttpResponseBadRequest()
    else:
        return HttpResponse("请求错误")


def verify_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect("/")
        else:
            return render_to_response('login.html',
                                      RequestContext(request, {'username': username, 'password_is_wrong': True}))


def ue_test(request):
    return render_to_response("ueTest.html")


def page_not_found(request):
    response = render_to_response('404.html')
    response.status_code = 404
    return response


def page_error(request):
    response = render_to_response('500.html')
    response.status_code = 500
    return response
